package com.yonyou.le.unattended.service;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yonyou.le.unattended.cache.DeviceCacheManager;
import com.yonyou.le.unattended.cache.MonitorCacheManager;
import com.yonyou.le.unattended.cache.entity.DeviceData;
import com.yonyou.le.unattended.delivery.entity.AdaptorParamVO;
import com.yonyou.le.unattended.exception.NoGateTargetAdaptorException;
import com.yonyou.le.unattended.exception.NoLEDTargetAdaptorException;
import com.yonyou.le.unattended.util.HttpRequestUtil;
import com.yonyou.le.unattended.util.ProConstant;

/**
 * 抬杆
 * 
 * @author zhangbbd
 *
 */
@Component
public class LedService {
	private Logger logger = LoggerFactory.getLogger(LedService.class);
	@Autowired
	private MonitorCacheManager monitorCacheManager;
	@Autowired
	private DeviceCacheManager deviceCacheManager;
	@Autowired
	private ProConstant constant;
	
	private final String MSG_STATUS="status";
	private final String MSG_RESULT="result";
//	private final String MSG_RESULT="result";
	private final String MSG_STATUS_RIGHT="1";
	private final String MSG_STATUS_WRONG="0";
	/**
	 * @param deviceCode
	 * @param ledText
	 * @throws NoGateTargetAdaptorException 
	 * 
	 **/
	public boolean showLed(String deviceCode,String ledText) throws NoLEDTargetAdaptorException {
		logger.debug("showLed:"+ledText);
		DeviceData deviceData = deviceCacheManager.getDeviceData(deviceCode,DeviceData.class);
		AdaptorParamVO adaptorParamVO = deviceData.getAdaptorParamVO();
		if(null == adaptorParamVO){
			throw new NoLEDTargetAdaptorException(deviceCode);
		}
		//service可配置。
		String url="http://"+adaptorParamVO.getHcadaptorip()+":"+adaptorParamVO.getHcadaptorport()+constant.showLedURL;
		Map<String, String> argMap = new HashMap<String, String>();
		argMap.put("deviceCode",deviceCode);
		argMap.put("ledText",ledText);
		
		Gson gson = new Gson();
		String result = HttpRequestUtil.jsonPOST(url, gson.toJson(argMap), "gbk");
		logger.debug("show Led result = " + result);
	    Map<String, String> map = gson.fromJson(result, new TypeToken<Map<String, String>>() {}.getType());
		if(MSG_STATUS_RIGHT.equals(map.get(MSG_STATUS))){
			String res=map.get(MSG_RESULT);
			if(BooleanUtils.toBoolean(res))
				return true;
			else
				return false;
		}else if(MSG_STATUS_WRONG.equals(map.get(MSG_STATUS))){
			return false;
		}
		return false;
	}

}